package com.sy.simpleegg.serialport.backscan.usb;

import android.os.Build;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;

import java.util.ArrayList;
import java.util.List;

public class ScanGunHelper {

    private final static long MESSAGE_DELAY = 200;

    private StringBuffer mStringBufferResult = new StringBuffer();

    private Handler mHandler = new Handler();

    private Runnable mScanningFishedRunnable = new Runnable() {
        @Override
        public void run() {
            performScanSuccess();
        }
    };


    private List<Integer> keyCodeList = new ArrayList<>();

    public ScanGunHelper() {

    }

    /**
     * 返回扫码成功后的结果
     */
    private void performScanSuccess() {
        try {

            boolean mCaps = keyCodeList.contains(KeyEvent.KEYCODE_SHIFT_RIGHT) || keyCodeList.contains(KeyEvent.KEYCODE_SHIFT_LEFT);

            for (int keyCode : keyCodeList) {

                char aChar = getInputCode(keyCode, mCaps);
                if (aChar != 0) {
                    mStringBufferResult.append(aChar);
                }
            }
            String barcode = mStringBufferResult.toString();

            Log.e("ScanGunHelper", "barcode==" + barcode);

            if (mScanGunListener != null && barcode.length() > 0){
                mScanGunListener.onScan(barcode);
            }

            mStringBufferResult.setLength(0);

            keyCodeList.clear();

            if (mHandler != null) {
                mHandler.removeCallbacks(mScanningFishedRunnable);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 扫码枪事件解析
     */
    public void analysisKeyEvent(KeyEvent event) {

        //Virtual是我所使用机器的内置软键盘的名字
        //在这判断是因为项目中避免和软键盘冲突（扫码枪和软键盘都属于按键事件）
        int keyCode = event.getKeyCode();

        if (event.getAction() == KeyEvent.ACTION_UP) {

            keyCodeList.add(keyCode);

            if (keyCode == KeyEvent.KEYCODE_ENTER) {
                mHandler.removeCallbacks(mScanningFishedRunnable);
                mHandler.post(mScanningFishedRunnable);
            } else {
                mHandler.removeCallbacks(mScanningFishedRunnable);
                mHandler.postDelayed(mScanningFishedRunnable, MESSAGE_DELAY);
            }
        }
    }


    //获取扫描内容
    private char getInputCode(int keyCode, boolean mCaps) {
        char aChar;
        if (keyCode >= KeyEvent.KEYCODE_A && keyCode <= KeyEvent.KEYCODE_Z) {
            //字母
            aChar = (char) ((mCaps ? 'A' : 'a') + keyCode - KeyEvent.KEYCODE_A);
        } else if (keyCode >= KeyEvent.KEYCODE_0 && keyCode <= KeyEvent.KEYCODE_9) {
            //数字
            aChar = (char) ('0' + keyCode - KeyEvent.KEYCODE_0);
        } else {
            //其他符号
            switch (keyCode) {
                case KeyEvent.KEYCODE_PERIOD:
                    aChar = '.';
                    break;
                case KeyEvent.KEYCODE_MINUS:
                    aChar = mCaps ? '_' : '-';
                    break;
                case KeyEvent.KEYCODE_SLASH:
                    aChar = '/';
                    break;
                case KeyEvent.KEYCODE_BACKSLASH:
                    aChar = mCaps ? '|' : '\\';
                    break;
                default:
                    aChar = 0;
                    break;
            }
        }
        return aChar;
    }

    /**
     * 输入设备是否存在
     */
    public boolean isScanGunExist(KeyEvent event) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Log.e("ScanGunHelper", "ProductId==" + event.getDevice().getProductId() + "，VendorId==" + event.getDevice().getVendorId());
            if (event.getDevice().getVendorId() == 1409 && event.getDevice().getProductId() == 262) {
                return true;
            }
        }
        return false;
    }

    public interface ScanGunListener{
        void onScan(String msg);
    }

    private ScanGunListener mScanGunListener;

    public void setScanGunListener(ScanGunListener scanGunListener){
        mScanGunListener = scanGunListener;
    }



}